package com.example.skyline.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.skyline.entity.User;
import com.example.skyline.exception.ServiceException;
import com.example.skyline.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {

    public static final String OPTIONS = "options";

    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if(OPTIONS.equalsIgnoreCase(request.getMethod())){
            return true;
        }

        String token = request.getHeader("token");

        if (StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }

        if(StrUtil.isBlank(token)){
            return false;
        }

        String userId;

        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException e){
            throw new ServiceException("401","请登录");
        }

        User user = userMapper.selectById(userId);
        if(user == null){
            throw new ServiceException("401","请登录");
        }

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();

        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException jwt){
            logger.error("JWT verification failed", jwt);
            throw new ServiceException("401","请登录");
        }

        return true;
    }
}
